import Fly from 'flyio/dist/npm/wx'
import { appEnv } from './utils'

let IsDev = process.env.NODE_ENV === 'development' || appEnv.isTest()
IsDev = true
console.log('使用测试环境api', IsDev)
const BASE_URL = 'https://www.ywwhbook.com'

const http = new Fly()

http.interceptors.request.use(request => {
  const tk = wx.getStorageSync('token')
  if (tk) {
    // request.headers['access-token'] = wx.getStorageSync('token')
    request.headers.accessToken = wx.getStorageSync('token')
    request.headers['content-type'] = 'application/json'
  }
})
http.interceptors.response.use(
  res => {
    console.log('----->', res.data)
    if (res.status == 200) {
      if (res.data.errorMsg) {
        wx.showModal({
          content: res.data.errorMsg,
          showCancel: false,
          confirmText: '确定'
        })
        return 'error'
      } else {
        return res.data.data
      }
    } else {
      wx.showModal({
        content: res.data.message,
        showCancel: false,
        confirmText: '确定'
      })
      return ''
    }
  },
  err => {
    console.log('error------>', err)

    if (err.message === 'request:fail timeout') {
      wx.showModal({
        content: '网络请求出错，请稍后重试',
        showCancel: false,
        confirmText: '确定'
      })
    } else if (err.status === 403) {
      wx.showModal({
        content: '请再次登录授权',
        showCancel: false,
        confirmText: '确定',
        success(res) {
          if (res.confirm) {
            wx.redirectTo({
              url: `/pages/Login`
            })
          }
        }
      })
    } else {
      wx.showModal({
        content: err.engine?.response?.errorMsg,
        showCancel: false,
        confirmText: '确定'
      })
    }
    return err
  }
)

export const login = data => http.get(`${BASE_URL}/userAuth/login`, data)

export const updateUser = data => http.post(`${BASE_URL}/userAuth/update`, data)

export const getSchool = () => http.get(`${BASE_URL}/school/getSchoolInfo`)

export const getCollege = id =>
  http.get(`${BASE_URL}/college/getCollegeInfo?schoolId=${id}`)

export const getMajor = id =>
  http.get(`${BASE_URL}/major/getMajorInfo?schoolId=${id}`)

export const getTeacher = () => http.get(`${BASE_URL}/teacher/getTeacherInfo`)

export const postTeacher = data =>
  http.post(`${BASE_URL}/teacher/addTeacherInfo`, data)

export const updateTeacher = data =>
  http.post(`${BASE_URL}/teacher/updateTeacherInfo`, data)

export const getBookList = data => http.post(`${BASE_URL}/book/list`, data)

export const addOrderInfo = data =>
  http.post(`${BASE_URL}/order/addOrderInfo`, data)

export const handBookInfo = data =>
  http.post(`${BASE_URL}/order/list/handBookInfo`, data)

export const getOrderList = () => http.get(`${BASE_URL}/order/list/reserve`)

export const updateOrderInfo = data =>
  http.post(`${BASE_URL}/order/updateOrderInfo`, data)
